package org.kernelab.basis.apps;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.kernelab.basis.gui.FilesFilter;
import org.kernelab.basis.gui.JTextAreaOutputStream;
import org.kernelab.basis.util.ExcelToSQL;

public class AppExcelToSQL extends JFrame
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1722307751465185029L;

	static {
		try {
			// UIManager.setLookAndFeel("avax.swing.plaf.metal.MetalLookAndFeel");

			// UIManager
			// .setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

			// UIManager
			// .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		new AppExcelToSQL();
	}

	private ExcelToSQL		parser;

	private JTextField		excelFilePath;

	private JButton			excelFileOpen;

	private JButton			parseButton;

	private JTextArea		resultTextArea;

	private JScrollPane		resultPane;

	private JProgressBar	parseProgress;

	private JTextField		sqlFilePath;

	private JButton			sqlFileOpen;

	public AppExcelToSQL()
	{
		super();

		this.config();

		this.arrange();
	}

	private void arrange()
	{
		final GridBagConstraints gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.CENTER;
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.insets = new Insets(1, 1, 1, 1);
		gbc.weightx = 1.0;
		gbc.weighty = 0.0;

		JPanel excelPanel = new JPanel(new GridBagLayout());
		excelPanel.add(this.getExcelFilePath(), gbc);
		gbc.gridx++;
		gbc.weightx = 0.0;
		excelPanel.add(this.getExcelFileOpen(), gbc);

		JPanel resultPanel = new JPanel(new GridBagLayout());
		gbc.gridx = 0;
		gbc.weightx = 1.0;
		gbc.weighty = 1.0;
		resultPanel.add(this.getResultPane(), gbc);
		gbc.fill = GridBagConstraints.VERTICAL;
		gbc.gridx++;
		gbc.weightx = 0.0;
		resultPanel.add(this.getParseButton(), gbc);

		JPanel sqlFilePanel = new JPanel(new GridBagLayout());
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridx = 0;
		gbc.weightx = 1.0;
		gbc.weighty = 0.0;
		sqlFilePanel.add(this.getSqlFilePath(), gbc);
		gbc.gridx++;
		gbc.weightx = 0.0;
		sqlFilePanel.add(this.getSqlFileOpen(), gbc);

		this.setLayout(new GridBagLayout());
		gbc.anchor = GridBagConstraints.CENTER;
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 1.0;
		gbc.weighty = 0.0;

		this.add(excelPanel, gbc);

		gbc.gridy++;
		gbc.weighty = 1.0;
		this.add(resultPanel, gbc);

		gbc.gridy++;
		gbc.weighty = 0.0;
		this.add(this.getParseProgress(), gbc);

		gbc.gridy++;
		this.add(sqlFilePanel, gbc);

		this.getResultPane().setPreferredSize(new Dimension(400, 300));

		this.pack();
		this.setVisible(true);
	}

	private void config()
	{
		this.setParser(new ExcelToSQL());
		this.getParser().getProgresses().add(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				getParseProgress().setValue(getParseProgress().getValue() + 1);
			}

		});

		this.setExcelFilePath(new JTextField());
		this.setExcelFileOpen(new JButton("Open Excel ..."));

		this.setParseButton(new JButton("Parse"));
		this.setResultTextArea(new JTextArea());
		this.getResultTextArea().setLineWrap(true);
		this.getResultTextArea().setEditable(false);
		this.setResultPane(new JScrollPane(this.getResultTextArea()));
		this.getResultPane().setHorizontalScrollBarPolicy(
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		this.getResultPane().setVerticalScrollBarPolicy(
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

		this.setParseProgress(new JProgressBar());
		this.getParseProgress().setStringPainted(true);

		this.setSqlFilePath(new JTextField());
		this.setSqlFileOpen(new JButton("Save As SQL ..."));

		this.getExcelFileOpen().addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				JFileChooser fc = new JFileChooser(".");
				fc.setDragEnabled(true);
				FilesFilter filter = new FilesFilter(new String("xls"));
				fc.addChoosableFileFilter(filter);

				if (fc.showOpenDialog(AppExcelToSQL.this) == JFileChooser.APPROVE_OPTION)
				{
					try {
						getExcelFilePath().setText(
								fc.getSelectedFile().getCanonicalPath()
										.replace('\\', '/'));
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}

		});

		this.getParseButton().addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				File file = new File(getExcelFilePath().getText());
				if (file.exists()) {
					getParser().setFile(file);
					getParser().setSheet(0);
					getParser().setWriter(
							new OutputStreamWriter(new JTextAreaOutputStream(
									getResultTextArea(), JTextAreaOutputStream.APPEND)));
					getParseProgress().setValue(0);
					getParseProgress().setMaximum(getParser().getSheet().getRows());
					Thread thread = new Thread(getParser());
					thread.start();
				}
			}

		});

		this.getSqlFileOpen().addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				if (new File(getExcelFilePath().getText()).exists()) {
					JFileChooser fc = new JFileChooser(".");
					fc.setDragEnabled(true);

					if (fc.showSaveDialog(AppExcelToSQL.this) == JFileChooser.APPROVE_OPTION)
					{
						File file = fc.getSelectedFile();

						try {
							getSqlFilePath().setText(
									file.getCanonicalPath().replace('\\', '/'));
						} catch (IOException e1) {
							e1.printStackTrace();
						}

						int result = JOptionPane.YES_OPTION;

						if (file.exists()) {
							result = JOptionPane.showConfirmDialog(AppExcelToSQL.this,
									file.getName() + " exists, overwrite it?",
									"File Exists", JOptionPane.YES_NO_OPTION,
									JOptionPane.QUESTION_MESSAGE);
						}

						if (result == JOptionPane.YES_OPTION) {
							try {
								getParser().setFile(
										new File(getExcelFilePath().getText()));
								getParser().setSheet(0);
								getParser().setWriter(new FileWriter(file));
								getParseProgress().setValue(0);
								getParseProgress().setMaximum(
										getParser().getSheet().getRows());
								Thread thread = new Thread(getParser());
								thread.start();
							} catch (IOException e2) {
								e2.printStackTrace();
							}
						}
					}
				}
			}
		});

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Excel TO SQL - KernelStudio.org");
	}

	public JButton getExcelFileOpen()
	{
		return excelFileOpen;
	}

	public JTextField getExcelFilePath()
	{
		return excelFilePath;
	}

	public JTextArea getResultTextArea()
	{
		return resultTextArea;
	}

	public JButton getSqlFileOpen()
	{
		return sqlFileOpen;
	}

	public JTextField getSqlFilePath()
	{
		return sqlFilePath;
	}

	public void setExcelFileOpen(JButton excelFileOpen)
	{
		this.excelFileOpen = excelFileOpen;
	}

	public void setExcelFilePath(JTextField excelFilePath)
	{
		this.excelFilePath = excelFilePath;
	}

	public void setResultTextArea(JTextArea resultTextArea)
	{
		this.resultTextArea = resultTextArea;
	}

	public void setSqlFileOpen(JButton sqlFileOpen)
	{
		this.sqlFileOpen = sqlFileOpen;
	}

	public void setSqlFilePath(JTextField sqlFilePath)
	{
		this.sqlFilePath = sqlFilePath;
	}

	public JButton getParseButton()
	{
		return parseButton;
	}

	public void setParseButton(JButton parseButton)
	{
		this.parseButton = parseButton;
	}

	public JProgressBar getParseProgress()
	{
		return parseProgress;
	}

	public void setParseProgress(JProgressBar parseProgress)
	{
		this.parseProgress = parseProgress;
	}

	public JScrollPane getResultPane()
	{
		return resultPane;
	}

	public void setResultPane(JScrollPane resultPane)
	{
		this.resultPane = resultPane;
	}

	public ExcelToSQL getParser()
	{
		return parser;
	}

	private void setParser(ExcelToSQL parser)
	{
		this.parser = parser;
	}

}
